<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>待办事项</title>
    <style>
        .p{
            width: 180px;
            height: 20px;
        }

    </style>
</head>
<body onload="todolist()">
    <div id="taskList">
        <h1>待办事项清单</h1>
        <input class="p" type="text" id="todoTitle"value='添加新事项' name="list">
        <input type="submit" id="addbutton" value="+" onclick="submit()" ></p>

        <ul id="listBox">

        </ul>
    </div>
    <script>
        function todolist(){
            fetch("/todos")
                .then(function(response){
                    return response.json();
                }).then(function(data){
                    document.getElementById("listBox").innerHTML="";
                    var openData=data.todos;
                    console.log(openData)
                    for(var i=0;i<openData.length;i++){
                        if(!openData[i].completed){
                            var opt='<li>'+openData[i].title+'</ul>'
                            document.getElementById('listBox').innerHTML += opt;
                        }
                    }
                });
        }
        function submit(){
            let value=document.getElementsByName("list")[0].value;
            let opts={
                method:'post',
                headers:{
                    'Content-Type':'application/x-www-form-urlencoded;'
                },
                body:"title="+value,
            }
            fetch('/todos',opts).then(response=>{
                let result =response.text();
                result.then(res=>{
                    document.getElementById('todoTitle').value = ""
                    todolist();
                })
            })
        }
    function Finish(id){
        let opts={
            method:"get",
            headers:{
                'Content-Type':'application/x-www-form-urlencoded'
            },
        }
        fetch('/todos/mark_completed'+'?todo_id='+id,opts).then(response=>{
            let result=response.text();
            result.then(res=>{
                todolist();
            })
        })
    }
    function isFinish(id){
        if(id){
            Finish(id);
            todolist();
        }
    }

    </script>
</body>
</html>